import { AsyncRouterMap,ConstRouterMap } from '@/router'
import router from '@/router'

/**
 * 判断该路由的子路由是否都是启用状态
 * @param {*} param0 
 */
function childVisible({children}) {
    if(children==undefined) return true;
    return children.some((v)=> v.visible); 
}

/**
 * 路由菜单动态切换配置
 * @param {Array} routes (自定义权限菜单,从数据库读取，按角色自定义配置)
 * @param {Array} constRouter (前端路由数组)
 * @param {Array} router (目标路由【该角色用户可访问的路由】)
 */
function setRoute(routes, constRouter, router) {
    routes.forEach((v,index) => {
        (constRouter.filter(child => {
            // 如果自定义的权限菜单中的visible为true而且他的子路由也都为true则筛选出当前路由
            if (v.visible == true  && v.routeName == child.path){
                // 按钮级权限配置(页面上直接判断v-if=>$route.meta.auth)
                (v.auth)&&(child.meta.auth = v.auth)
                return child
            }
        })).forEach(route => { 
            // 将最终筛选出的路由存进目标路由 
            router.push({...route})
        })
        // 递归设置children子路由
        if(v.children&&router[index]&&v.children.length>0)
            setRoute(v.children,router[index].children,router[index].children=[])
    })
}

const permission = {
    state: {
        routers: ConstRouterMap,
        addRouters: []
    },
    mutations: {
        SET_ROUTERS: (state, routers) => {
            state.addRouters = routers
            state.routers = ConstRouterMap.concat(routers)
            // 载入路由
            router.addRoutes(routers)
        }
    },
    actions: {
        switchRoutes({commit}, group) {
            var router = []
            return new Promise(resolve => {
                // 设置路由
                if(group.children){
                    setRoute(group.children, AsyncRouterMap, router)
                    commit('SET_ROUTERS', router);
                }
                resolve(router);
            })
        }
    }
}

export default permission;